<?php

namespace App\Repositories;

use App\Models\Order;
use DB;
/**
 * @auther 商品规格属性
 */

class OrderRepository
{

    // 列表
    public function list($where = [])
    {
        return Order::where($where)->orderBy('created_at', 'desc')
            ->get();
    }
    // 分页列表
    public function pageList($where = [])
    {
        !isset($where['page']) ? $page = 15 : $page = $where['page'];

        return $userList = Order::orderBy('created_at', 'desc')->where(function ($query) use ($where) {
                if (isset($where['start_time']) && isset($where['end_time'])) {
                    $query->whereBetween('created_at', [$where['start_time'],$where['end_time']]);      
                }
                if (isset($where['search'])) {
                    $query->where('username', 'like', '%' . $where['search'] . '%')
                          ->orWhere('mobile', 'like', '%' . $where['search'] . '%')
                          ->orWhere('order_sn', 'like', '%' . $where['search'] . '%');
                }
                
        })->paginate($page);
    }

    // add
    public function create($param)
    {
        $sys = new Order();
        $sys->fill($param)->save();
        return $sys->id;
    }

    // update
    public function update($param)
    {
        $sys = Order::find($param['id']);
        return $sys->fill($param)->save();
    }

    // del
    public function delete($id)
    {
        return Order::where('id', $id)->delete();
    }

    // info
    public function info($param)
    {
        return Order::with('orderPro')->where($param)->first();
    }
       // 计算今日订单数（已支付）
    public function countzsa($param=[])
    {
        return Order::whereIn('state',[2,3])->where('created_at', '>=', $param['start_time'])
            ->where('created_at', '<=', $param['end_time'])->count();
    }
    // 计算今日收款
    public function countzse($param=[])
    {
        return Order::whereIn('state',[2,3])->where('created_at', '>=', $param['start_time'])
            ->where('created_at', '<=', $param['end_time'])->sum('price');
    }
    public function orderStatistics($param=[])
    {
        return Order::whereIn('state',[2,3])->where('created_at', '<=', $param['start_time'])
            ->select([DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date"), DB::raw('SUM(price) as value')])
            ->where('created_at', '>=', $param['end_time'])
            ->groupBy(DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))->get();
    }
}
